import axios from 'axios'

import _ from 'lodash'

import { url, api } from 'config/api'

const initState = () => ({
  loading: false,
  init: false,
  msg: '',

  query: {},
  data: []
})

const action_loading = 'dict_bank/loading'
const action_loaded = 'dict_bank/loaded'
const action_fail = 'dict_bank/fail'
const action_success = 'dict_bank/success'

const loading = payload => ({ payload, type: action_loading })
const loaded = payload => ({ payload, type: action_loaded })
const fail = payload => ({ payload, type: action_fail })
const success = payload => ({ payload, type: action_success })

export function reducer (state = initState(), action) {
  const {
    payload = {},
    type
  } = action

  switch (type) {
    case action_loading:
      return {
        ...state,

        msg: '',
        loading: true
      }
    case action_loaded:
      return {
        ...state,

        loading: false
      }
    case action_fail:
      return {
        ...state,

        msg: payload
      }
    case action_success:
      return {
        ...state,
        ...payload,

        init: true
      }

    default:
      return state
  }
}

export function getData (payload = {}, ignoreCache) {
  return async (dispatch, getState) => {
    const {
      dict_bank: {
        loading: _loading,
        query,
        init,
        data
      }
    } = getState()

    if (_loading) {
      return ['重复请求']
    }

    const assignQuery = {
      ...query,
      ...payload
    }

    if (
      init &&
      !ignoreCache &&
      !_.isEqual(assignQuery, payload)
    ) {
      return [null, data]
    }

    dispatch(loading())

    const [err, res] = await axios.post(url.server + api.dict.bank, assignQuery)

    dispatch(loaded())

    if (err) {
      dispatch(fail(err))

      return [err]
    }

    dispatch(success({
      query: assignQuery,
      data: res.data
    }))

    return [null, res]
  }
}
